/*
navclouder.js

Web worker. http://www.whatwg.org/specs/web-workers/current-work/

Child Cloud generator
Sit around and wait for weighted list generation work

This requires json.js - make sure you pack them together before deploying.
*/

// Begin normal stuff
var db = openDatabase('minerva.web.db', '1.0', 'Minerva DB', 1024*1024*5);

onmessage = function(event) {
  // Generate cloud of children for url
  var parent_path = event.data;
  generateTagCloudData(parent_path); // generateTagCloudData will postMessage
  };


onerror = function(event) {
  var err = event.data;
  postMessage('ERROR: ' + err);
  };


var generateTagCloudData = function(parent_path) {
  // First get all paths that have url as a parent
  var tags = {};
  var pathmap = {};
  db.transaction(function(tx) { 
    tx.executeSql(
      'select path from NounEvents where path like ?', [parent_path+'%'],
      function(tx, results) { 
        var len = results.rows.length;
        for (var i = 0; i < len; i++) { 
          var path = results.rows.item(i).path;
          var sub = path.slice(parent_path.length);
          var words = sub.split('/');
          for (var j = 0; j < words.length; j++) {
            var w = words[j];
            var previous = tags[w];
            if (previous) {
              tags[w] += 1;
              if (w == words.slice(-1)) pathmap[w] = path;
            }
            else {
              tags[w] = 1;
              pathmap[w] = path;
            }
          }
        }
        var data = [tags, pathmap];
        var msg = JSON.stringify([parent_path, data]);
        postMessage(msg);
      }, function(tx, error) {}
    );
  });
};
